package cn.woochen.mvvmframe.config.status

import kotlinx.coroutines.flow.MutableSharedFlow


/**
 * 自定义结果集封装类
 */
sealed class ResultState<out T> {
    companion object {
        fun <T> onAppSuccess(data: T?, code: String, message: String, extParams: Any): ResultState<T> =
            Success(data, code, message, extParams)

        fun <T> onAppError(error: CustomException, extParams: Any): ResultState<T> = Error(error, extParams)
    }

    data class Success<out T>(val data: T?, val code: String, val message: String, val extParams: Any) : ResultState<T>()
    data class Error(val error: CustomException, val extParams: Any) : ResultState<Nothing>()
    data class Empty(val extParams: Any = "") : ResultState<Nothing>()
}

suspend fun <T> MutableSharedFlow<ResultState<T>>.paresResult(result: BaseBean<T>, extParams: Any) {
    if (ErrorCode.successCodes.contains(result.errorCode)) {
        emit(ResultState.onAppSuccess(result.data, result.errorCode, result.errorMsg, extParams))
    } else {
        emit(ResultState.onAppError(CustomException(result.errorCode, result.errorMsg), extParams))
    }
}

/**
 * 异常转换异常处理
 */
suspend fun <T> MutableSharedFlow<ResultState<T>>.paresException(e: Throwable, extParams: Any) {
    if (e is CustomException) {
        ErrorCodeHandleHelper.exceptionCodeHandle(e)
        when (e.code) {
            ErrorCode.REPEAT_REQUEST -> {//重复请求

            }
            else -> {
                emit(ResultState.onAppError(e, extParams))
            }
        }

    } else {
        emit(ResultState.onAppError(CustomException(e), extParams))
    }
}



